// app/model/user_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, ENUM } = app.Sequelize;

  const User = app.model.define('user', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: STRING(50),
      allowNull: false,
      comment: '用户姓名'
    },
    email: {
      type: STRING(100),
      allowNull: false,
      unique: true,
      comment: '邮箱'
    },
    password: {
      type: STRING(100),
      allowNull: false,
      comment: '密码'
    },
    role: {
      type: ENUM('admin', 'user', 'auditor'),
      allowNull: false,
      defaultValue: 'user',
      comment: '角色'
    },
    status: {
      type: ENUM('active', 'inactive', 'locked'),
      allowNull: false,
      defaultValue: 'active',
      comment: '状态'
    },
    lastLoginAt: {
      type: DATE,
      allowNull: true,
      comment: '最后登录时间'
    }
  }, {
    tableName: 'users',
    underscored: true,
    comment: '用户表'
  });

  // 添加关联关系
  User.associate = function() {
    // 用户与组织的多对多关系
    if (app.model.OrganizationModel && app.model.UserOrganizationModel) {
      User.belongsToMany(app.model.OrganizationModel, {
        through: app.model.UserOrganizationModel,
        foreignKey: 'user_id',
        otherKey: 'organization_id',
        as: 'organizations'
      });
    }
  };

  return User;
};